import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { PlusOutlined, HistoryOutlined, DownOutlined, UploadOutlined } from '@ant-design/icons';
import { message, Upload, Modal } from 'antd';
import { useAuth } from '@/app/auth';
import { RootState } from '@/store';
import { updateCurrentChat, clearHistoryMsg, setHistoryMsg, clearCurrentMsg } from '@/store/slices/room';
import { sidebarEvents } from '@/store/hooks/useSidebar';
import { getChatHistory, ChatHistory, getChatHistoryDetail, SessionHistoryData } from '@/services/chatHistory';
import { uploadResume } from '@/services/resume';
import styles from './index.module.less';
import logger from '../../utils/logger';
import { useLeave } from '@/lib/useCommon';

function Sidebar(): React.ReactElement {
  const [isHistoryCollapsed, setIsHistoryCollapsed] = useState(false);
  const [historyList, setHistoryList] = useState<ChatHistory[]>([]);
  const [loading, setLoading] = useState(false);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [uploading, setUploading] = useState(false);
  const { isAuthenticated, user } = useAuth();
  const dispatch = useDispatch();
  const currentChatHistoryId = useSelector((state: RootState) => state.room.chatHistory?.id);
  const leaveRoom = useLeave();

  // 加载聊天详细记录
  const loadChatHistoryDetail = async (sessionId?: number) => {
    // 如果没有提供sessionId，则使用Redux中的当前聊天历史ID
    const targetSessionId = sessionId || currentChatHistoryId;
    if (!targetSessionId) {
      return;
    }

    try {
      // 先清空当前消息历史，确保没有残留消息
      dispatch(clearCurrentMsg());

      const response = await getChatHistoryDetail(targetSessionId);
      const historyData = response as SessionHistoryData;

      // 将获取到的消息历史更新到Redux状态
      if (historyData.messages && historyData.messages.length > 0) {
        // 确保消息有序处理
        const sortedMessages = [...historyData.messages].sort((a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime());

        // 一条一条地添加消息，确保状态更新
        for (const msg of sortedMessages) {
          dispatch(
            setHistoryMsg({
              text: msg.value,
              user: msg.user,
              paragraph: true,
              definite: true,
            })
          );
        }
      } else {
        logger.error('该聊天历史没有消息记录');
      }
    } catch (error) {
      logger.error('获取聊天历史详情失败:', error);
    }
  };

  // 处理历史项点击
  const handleHistoryItemClick = async (history: ChatHistory) => {
    try {
      // 尝试调用 leaveRoom 函数清理当前会话资源
      await leaveRoom();
    } catch (error) {
      console.error('离开房间时出错:', error);
      // 即使离开房间失败，也继续执行后续操作
    }

    // 切换到选中的聊天历史
    dispatch(updateCurrentChat(history));

    // 当点击历史记录项时，立即加载该会话的详细聊天记录
    if (history && history.id) {
      // 加载该会话的详细聊天记录
      loadChatHistoryDetail(history.id);
    }
  };

  // 处理新建会话点击
  const handleNewChatClick = () => {
    // 清除当前选中的聊天历史ID，触发创建新聊天
    dispatch(updateCurrentChat(null));
    // 清空消息历史
    dispatch(clearHistoryMsg());
  };

  // 处理上传简历点击
  const handleUploadResumeClick = () => {
    setUploadModalVisible(true);
  };

  // 处理文件上传前的验证
  const beforeUpload = (file: File) => {
    const isPDF = file.type === 'application/pdf';
    const isWord = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                  file.type === 'application/msword';
    
    if (!isPDF && !isWord) {
      message.error('只能上传PDF或Word文档！');
      return Upload.LIST_IGNORE;
    }
    
    return true;
  };

  // 处理文件上传
  const handleUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    
    try {
      setUploading(true);
      // uploadResume实际返回的是response.data，可能为null
      const result = await uploadResume(file);
      // 如果请求成功，result可能是null，这是正常的
      message.success('简历上传成功！');
      setUploading(false);
      setUploadModalVisible(false);
      // 返回result或空对象，确保onSuccess总是有值
      onSuccess(result || {});
    } catch (error: any) {
      message.error(error.message || '简历上传失败，请重试');
      setUploading(false);
      onError(error);
    }
  };

  const fetchHistoryList = async () => {
    if (!isAuthenticated || !user?.userId) return;

    try {
      setLoading(true);
      const history = await getChatHistory();
      setHistoryList(history || []);

      // 如果没有选中的聊天历史ID，并且有历史记录，选择第一条
      if (history && history.length > 0 && !currentChatHistoryId) {
        dispatch(updateCurrentChat(history[0]));
        handleHistoryItemClick(history[0]);
      }
    } catch (error) {
      logger.error('获取历史记录失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchHistoryList();

    // 注册侧边栏刷新事件
    const unregister = sidebarEvents.register(fetchHistoryList);

    // 组件卸载时取消注册
    return () => {
      unregister();
    };
  }, [isAuthenticated, user?.userId]);

  return (
    <div className={styles.sidebar}>
      <div className={styles.logo}>
        <span>即刻面</span>
      </div>

      <div className={styles.menuList}>
        <div className={styles.menuItem} onClick={handleNewChatClick}>
          <PlusOutlined />
          <span>新建会话</span>
        </div>

        <div className={styles.menuItem} onClick={handleUploadResumeClick}>
          <UploadOutlined />
          <span>上传简历</span>
        </div>

        {isAuthenticated && (
          <>
            <div className={`${styles.menuItem} ${styles.historyMenuItem}`} onClick={() => setIsHistoryCollapsed(!isHistoryCollapsed)}>
              <HistoryOutlined />
              <span>历史会话</span>
              <DownOutlined className={`${styles.arrow} ${isHistoryCollapsed ? styles.collapsed : ''}`} />
            </div>

            <div className={`${styles.historyList} ${isHistoryCollapsed ? styles.collapsed : ''}`}>
              {loading ? (
                <div className={styles.loading}>加载中...</div>
              ) : (
                historyList.map((history) => (
                  <div key={history.id} className={`${styles.historyItem} ${history.id === currentChatHistoryId ? styles.active : ''}`} onClick={() => handleHistoryItemClick(history)}>
                    {history.title}
                  </div>
                ))
              )}
            </div>

            <div className={`${styles.viewAll} ${isHistoryCollapsed ? styles.collapsed : ''}`}>
              <span>查看全部</span>
            </div>
          </>
        )}
      </div>

      <Modal
        title="上传简历"
        open={uploadModalVisible}
        onCancel={() => {
          if (!uploading) {
            setUploadModalVisible(false);
          }
        }}
        footer={null}
        maskClosable={!uploading}
        closable={!uploading}
      >
        <p>请上传您的PDF或Word格式简历文件</p>
        <Upload.Dragger
          name="file"
          customRequest={handleUpload}
          beforeUpload={beforeUpload}
          maxCount={1}
          disabled={uploading}
          showUploadList={{
            showRemoveIcon: !uploading,
            showPreviewIcon: false
          }}
        >
          {uploading ? (
            <div className={styles.uploadingContainer}>
              <div className={styles.loadingSpinner} />
              <p>简历上传中，请稍候...</p>
            </div>
          ) : (
            <>
              <p className="ant-upload-drag-icon">
                <UploadOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">支持PDF、DOC、DOCX格式</p>
            </>
          )}
        </Upload.Dragger>
      </Modal>
    </div>
  );
}

export default Sidebar;
